package xyz.gits.modules.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.gits.modules.base.GitsBaseController;
import xyz.gits.modules.system.dto.UserDTO;
import xyz.gits.modules.system.service.IMailService;

/**
 * @author: 读钓
 * @date 2019-05-18 下午 7:44
 */
@Controller
@Slf4j
@Api(tags = "用户模块")
@RequestMapping("/user")
public class UserController extends GitsBaseController {

    private String prefix = "gits/user";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private IMailService mailService;

    @GetMapping("/registered")
    public String registered() {
        return prefix + "/registered";
    }

    @ApiOperation("用户注册")
    @RequiresPermissions("gits:user:registered")
    @Log(title = "用户注册", businessType = BusinessType.INSERT)
    @PostMapping("/registered")
    @ResponseBody
    public AjaxResult userRegistered(UserDTO dto) {
        SysUser user = new SysUser();
        BeanUtil.copyProperties(dto, user, CopyOptions.create().ignoreNullValue());
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(dto.getLoginName(),
                dto.getPassword(), user.getSalt()));
        return toAjax(userService.insertUser(user));
    }

    @ApiOperation("发送邮箱验证码")
    @RequiresPermissions("gits:user:mailCode")
    @PostMapping("/mail/code")
    @ResponseBody
    public AjaxResult mailVerify(String longinName, String email) throws Exception {
        if (StrUtil.isBlank(longinName)) {
            longinName = ShiroUtils.getLoginName();
        }
        return toAjax(mailService.sendCodeVerify(longinName, email));
    }
}